<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/26
 * Time: 15:46
 */

namespace We7\Dev\DebugBar\W7;


use DebugBar\DataCollector\PDO\PDOCollector;
use DebugBar\DataCollector\PDO\TraceablePDO;
use DebugBar\DataCollector\TimeDataCollector;

class W7PDOCollector extends PDOCollector
{
	public function __construct(TraceablePDO $pdo = null, TimeDataCollector $timeCollector = null)
	{
		parent::__construct($pdo, $timeCollector);
	}
	/**
	 * Collects data from a single TraceablePDO instance
	 *
	 * @param TraceablePDO $pdo
	 * @param TimeDataCollector $timeCollector
	 * @param string|null $connectionName the pdo connection (eg default | read | write)
	 * @return array
	 */
	protected function collectPDO(TraceablePDO $pdo, TimeDataCollector $timeCollector = null, $connectionName = null)
	{
		if (empty($connectionName) || $connectionName == 'default') {
			$connectionName = 'pdo';
		} else {
			$connectionName = 'pdo ' . $connectionName;
		}
		$stmts = array();
		$index = 0;
		foreach ($pdo->getExecutedStatements() as $stmt) {


			$stmts[] = array(
				'sql' => $this->renderSqlWithParams ? $stmt->getSqlWithParams($this->sqlQuotationChar) : $stmt->getSql(),
				'row_count' => $stmt->getRowCount(),
				'stmt_id' => $stmt->getPreparedId(),
				'prepared_stmt' => $stmt->getSql(),
				'params' => $stmt->getParameters() + ($stmt instanceof W7TracedStatement ? $stmt->getSource() : array()),
				'duration' => $stmt->getDuration(),
				'duration_str' => $this->getDataFormatter()->formatDuration($stmt->getDuration()),
				'memory' => $stmt->getMemoryUsage(),
				'memory_str' => $this->getDataFormatter()->formatBytes($stmt->getMemoryUsage()),
				'end_memory' => $stmt->getEndMemory(),
				'end_memory_str' => $this->getDataFormatter()->formatBytes($stmt->getEndMemory()),
				'is_success' => $stmt->isSuccess(),
				'error_code' => $stmt->getErrorCode(),
				'error_message' => $stmt->getErrorMessage()
			);
			if ($timeCollector !== null) {
				$timeCollector->addMeasure($stmt->getSql(), $stmt->getStartTime(), $stmt->getEndTime(), array(), $connectionName);
			}
		}

		return array(
			'nb_statements' => count($stmts),
			'nb_failed_statements' => count($pdo->getFailedExecutedStatements()),
			'accumulated_duration' => $pdo->getAccumulatedStatementsDuration(),
			'accumulated_duration_str' => $this->getDataFormatter()->formatDuration($pdo->getAccumulatedStatementsDuration()),
			'memory_usage' => $pdo->getMemoryUsage(),
			'memory_usage_str' => $this->getDataFormatter()->formatBytes($pdo->getPeakMemoryUsage()),
			'peak_memory_usage' => $pdo->getPeakMemoryUsage(),
			'peak_memory_usage_str' => $this->getDataFormatter()->formatBytes($pdo->getPeakMemoryUsage()),
			'statements' => $stmts
		);
	}
}